package com.heatup.apt.management.service.coupon.impl;

import com.heatup.apt.common.constants.CouponConstants;
import com.heatup.apt.common.dao.CouponApiResultMapper;
import com.heatup.apt.common.dao.CouponCheckMapper;
import com.heatup.apt.common.dao.CouponDetailMapper;
import com.heatup.apt.common.dao.CouponInfoMapper;
import com.heatup.apt.common.util.CouponUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.management.service.coupon.CouponService;
import com.heatup.apt.management.util.ExcelDocumentor;
import com.heatup.apt.management.util.GenerateShortUrlUtil;
import com.heatup.apt.management.util.ManageConfigPropertiesUtil;
import com.heatup.apt.model.api.coupon.CouponApiResultModel;
import com.heatup.apt.model.coupon.CouponCheck;
import com.heatup.apt.model.coupon.CouponDetail;
import com.heatup.apt.model.coupon.CouponInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠券服务实现类
 *
 * @author: Blank
 * @create: 2016-11-25-上午 10:00
 */
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    CouponInfoMapper couponInfoMapper;
    @Autowired
    CouponCheckMapper couponCheckMapper;
    @Autowired
    CouponDetailMapper couponDetailMapper;
    @Autowired
    CouponApiResultMapper couponApiResultMapper;
   
    
    

    /**
     * 保存优惠券信息
     *
     * @param couponInfo
     * @param userName
     * @return
     */
    @Override
    public int saveCoupon(CouponInfo couponInfo, String userName) {
        if (couponInfo == null)
            return 0;
        int result;
        if (couponInfo.getId() == null) {
            if (couponInfo.getIsLimitCourse().intValue() == 1) {
                    couponInfo.setLimitTeamCourse(1);
                    couponInfo.setLimitCampCourse(1);
                    couponInfo.setLimitSecretCourse(1);
                    couponInfo.setLimitSelfCourse(1);
            } else {
                if(couponInfo.getLimitTeamCourse() == null){
                    couponInfo.setLimitTeamCourse(0);
                }
                if(couponInfo.getLimitCampCourse() == null){
                    couponInfo.setLimitCampCourse(0);
                }
                if(couponInfo.getLimitSecretCourse() == null){
                    couponInfo.setLimitSecretCourse(0);
                }
                if(couponInfo.getLimitSelfCourse() == null){
                    couponInfo.setLimitSelfCourse(0);
                }
            }

            //私教不包含课程体验券 modify by earvin
            if(couponInfo.getCouponType().intValue()==CouponConstants.CouponType_Course){
                couponInfo.setLimitSecretCourse(0);
            }

            if(couponInfo.getCouponType().intValue() == 5){
            	couponInfo.setIsLimitCourse(2);
            	couponInfo.setLimitTeamCourse(1);
            }
            couponInfo.setCouponStatus(1);
            couponInfo.setCreatedBy(userName);
            couponInfo.setCreateTime(new Date());
            result = couponInfoMapper.insertSelective(couponInfo);
        } else {
            couponInfo.setUpdatedBy(userName);
            couponInfo.setUpdatedTime(new Date());
            result = couponInfoMapper.updateSelectiveById(couponInfo);
        }
        return result;
    }

    /**
     * 查询优惠券校验人列表
     * @param type 1 优惠券校验人列表 2客户经理列表
     * @return
     */
    @Override
    public List<CouponCheck> queryAllCheckList(Integer type) {
        return couponCheckMapper.queryAllCheckList(type);
    }

    /**
     * 优惠券分页查询
     *
     * @param paramsMap
     * @return
     */
    @Override
    public Map<String, Object> queryCouponList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap();
        paramsMap.put("pageNo",(Integer)paramsMap.get("pageIndex") * (Integer)paramsMap.get("pageSize"));
        resultMap.put("couponList", couponInfoMapper.queryCouponList(paramsMap));
        resultMap.put("couponCount", couponInfoMapper.queryCouponCount(paramsMap));

        return resultMap;
    }

    /**
     * 优惠券查询
     *
     * @param id 主键
     * @return
     */
    @Override
    public CouponInfo queryById(Integer id) {
        return couponInfoMapper.queryById(id);
    }

    /**
     * 更新优惠券上线
     *
     * @param id 主键
     * @param checkName 审核人
     * @param checkPhone 手机号
     * @return
     */
    @Override
    public int updateCouponToOnline(Integer id, String checkName, String checkPhone) {
        CouponInfo couponInfo = queryById(id);
        couponInfo.setCheckName(checkName);
        couponInfo.setCheckPhone(checkPhone);
        couponInfo.setCouponStatus(CouponConstants.CouponStatus_Online);
        couponInfo.setCheckTime(new Date());
        return couponInfoMapper.updateSelectiveById(couponInfo);
    }

    /**
     * 更新优惠券下架
     *
     * @param id 主键
     * @return
     */
    @Override
    public int updateCouponToOffline(Integer id) {
        //作废还未领取的优惠券
        couponDetailMapper.updateCouponToOfflineByCouponId(id);
        CouponInfo couponInfo = queryById(id);
        couponInfo.setCouponStatus(CouponConstants.CouponStatus_Offline);
        return couponInfoMapper.updateSelectiveById(couponInfo);
    }
    /**
     * @author Earvin
     * @see //按照批次信息生成兑换码,如果获取方式是1：用户输入码，则直接使用couponInfo里面的兑换码；
     * @see //如果兑换方式为2：系统自动生成：兑换码==4位批次+12位不重复的字符串组合。保证唯一性。
     * @param couponId 兑换券批次ID
     * @return String couponCode 兑换码
     */
    @Override
    public String generatorCouponCodeBy(Integer couponId) {
        CouponInfo couponInfo = couponInfoMapper.queryById(couponId);
        if (couponInfo != null) {
            // 如果获取方式是用户输入兑换码领取，表示兑换码已固定，否则则生成兑换码
            if ("1".equals(couponInfo.getGetMode())) {
                return couponInfo.getCouponCode();
            } else {
                String couponCode = null;
                // 从数据库查询出是否存在兑换码，如果有责从新生成。
                while (true) {
                    couponCode = CouponUtil.generatorCoupinCode(couponId);
                    CouponDetail couponDetail = couponDetailMapper.selectByCouponCode(couponCode);
                    if (couponDetail == null) {
                        break;
                    }
                }
                return couponCode;
            }
        } else {
            return null;
        }
    }

    /**
     * 查询指定优惠券领取记录
     *
     * @param paramsMap 查询条件
     * @return
     */
    @Override
    public Map<String, Object> queryCouponGetHistoryList(Map<String,Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap();
        paramsMap.put("pageNo",(Integer)paramsMap.get("pageIndex") * (Integer)paramsMap.get("pageSize"));
        resultMap.put("couponDetailList", couponDetailMapper.queryCouponDetailList(paramsMap));
        resultMap.put("couponDetailCount", couponDetailMapper.queryCouponDetailCount(paramsMap));
        resultMap.put("couponGetCount", couponDetailMapper.queryCouponGetCount(paramsMap));
        resultMap.put("couponUsedCount", couponDetailMapper.queryCouponUsedCount(paramsMap));

        return resultMap;
    }

    /**
     * 分页查询优惠券新增(审核)
     *
     * @param paramsMap 查询条件
     * @return
     */
    @Override
    public Map<String, Object> queryCouponAddList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap();
        paramsMap.put("pageNo",(Integer)paramsMap.get("pageIndex") * (Integer)paramsMap.get("pageSize"));
        resultMap.put("couponCheckList", couponInfoMapper.queryCouponCheckList(paramsMap));
        resultMap.put("couponCheckCount", couponInfoMapper.queryCouponCheckCount(paramsMap));

        return resultMap;
    }

    /**
     * 检查优惠券是否存在名称相同时 兑换时间/使用时间冲突
     *
     * @param couponInfo
     * @return true 存在/false 不存在
     */
    @Override
    public boolean checkByName(CouponInfo couponInfo) {
        CouponInfo couponInfoDB = couponInfoMapper.queryByName(couponInfo.getCouponCode());
        if (couponInfoDB !=null ) {

            if(couponInfo.getChangeMode().intValue() ==1
                    && couponInfo.getChangeMode().intValue() == couponInfoDB.getChangeMode().intValue()
                    ){
                //保存/数据库兑换都是不限
                return true;
            }
            if(couponInfo.getChangeMode().intValue() == 1 && couponInfoDB.getChangeMode().intValue() == 2
                    || couponInfo.getChangeMode().intValue() == 2 && couponInfoDB.getChangeMode().intValue() ==1){
                //保存/但数据库中的 兑换日期不限 兑换开始/结束时间有限 也冲突
                return true;
            }
            if (couponInfo.getChangeMode().intValue() ==2
                    && couponInfo.getChangeMode().intValue() == couponInfoDB.getChangeMode().intValue()) {
                //保存兑换开始或结束日期相同
                if (couponInfo.getChangeBeginDate().compareTo(couponInfoDB.getChangeBeginDate()) == 0
                        || couponInfo.getChangeEndDate().compareTo(couponInfoDB.getChangeEndDate()) == 0) {
                    return true;
                }
                //保存兑换开始时间 小于数据库中结束时间
                if (couponInfo.getChangeBeginDate().before(couponInfoDB.getChangeEndDate())) {
                    return true;
                }
                //保存兑换结束时间 小于数据库中开始时间
                if (couponInfo.getChangeEndDate().before(couponInfoDB.getChangeBeginDate())) {
                    return true;
                }
            }
            if(couponInfo.getUseMode().intValue() == 1
                    && couponInfo.getUseMode().intValue() == couponInfoDB.getUseMode().intValue()){
                //保存/数据库 使用模式都是领用日起算
                return true;
            }
            if(couponInfo.getUseMode().intValue() ==1 && couponInfoDB.getUseMode().intValue() ==2
                    || couponInfo.getUseMode().intValue() == 2 && couponInfoDB.getUseMode().intValue() == 1){
                //保存/数据库 使用模式不同 也冲突
                return true;
            }
            if(couponInfo.getUseMode().intValue() == 2
                    && couponInfo.getUseMode().intValue() == couponInfoDB.getUseMode().intValue()){
                //使用开始/或结束日期相同
                if(couponInfo.getUseBeginDate().compareTo(couponInfoDB.getUseBeginDate()) == 0
                        ||couponInfo.getUseEndDate().compareTo(couponInfoDB.getUseEndDate()) == 0){
                    return true;
                }
                //保存使用开始时间 小于数据库中结束时间
                if (couponInfo.getUseBeginDate().before(couponInfoDB.getUseEndDate())) {
                    return true;
                }
                //保存使用结束时间 小于数据库中开始时间
                if (couponInfo.getUseEndDate().before(couponInfoDB.getUseBeginDate())) {
                    return true;
                }

            }

        }
        return false;
    }
    
    @Override
	public Map<String, Object> downAndGeneratorCouponDetailInfo(Integer id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("coupon_id", id);
		paramsMap.put("is_geted",0);
		CouponInfo couponInfo = couponInfoMapper.queryById(id);
		//判断是否生成优惠券明细
		if (couponInfo != null) {
			//有数量限制才需生成优惠券信息
			if(couponInfo.getMaxCount()>0){
				int count = couponApiResultMapper.queryCountUserCouponListBy(paramsMap);
				//如果查询的优惠券明细数据为0，则表示需要生成优惠券数据。
				if(count<=0){
					//List<CouponDetail> couponDetails = new ArrayList<CouponDetail>();
					for (int i = 0; i < couponInfo.getMaxCount(); i++) {
//						CouponApiResultModel resultModel = new CouponApiResultModel();
						CouponDetail couponDetail = new CouponDetail();
						couponDetail.setCouponId(id);
						String couponCode = this.generatorCouponCodeBy(id);
						couponDetail.setCouponCode(couponCode);
						couponDetail.setMakeTime(new Date());
						couponDetail.setIsValid(1);
						//couponDetails.add(couponDetail);
						couponDetailMapper.insertSelective(couponDetail);
					}
					/**
					if (couponDetails.size() > 0) {
						// 批量插入数据优惠券明细数据
						couponDetailMapper.insertCouponDetailsBatch(couponDetails);
					}*/
				}
			}
		}else{
			resultMap.put("msg", "没有优惠券信息");
			resultMap.put("result", "error");
			return resultMap;
		}
		//生成excel数据
		List<CouponApiResultModel>	list = couponApiResultMapper.queryUserCouponListBy(paramsMap);
		
		String couponCodeUrl = ManageConfigPropertiesUtil.getString("coupon_code_url");
		if (list != null) {
			for (CouponApiResultModel result : list) {
				String coupon_code_url = couponCodeUrl.replace("{couponcode}", result.getCoupon_code());
				result.setCoupon_code_url(coupon_code_url);
				String shor_coupon_url = null;
				int i=0;
				while (true) {
					shor_coupon_url = GenerateShortUrlUtil.generateShortUrl(coupon_code_url);
					if ((shor_coupon_url != null && !"".equals(shor_coupon_url)) || i>1 ) {
						break;
					}
					i = i++;
				}
				result.setCoupon_short_url(shor_coupon_url);
			}
			String fileName = this.downloadCouponDetail(list);
			resultMap.put("fileName", fileName);
			resultMap.put("result", "success");
			resultMap.put("msg", "export success");
		} else {
			resultMap.put("result", "error");
			resultMap.put("msg", "没有优惠券数据");
		}
		return resultMap;
	}

	private String downloadCouponDetail(List<CouponApiResultModel> list) {
		String downloadPath = ManageConfigPropertiesUtil.getString("uploadImagDir");
		String fileName = "CouponDetail" + System.currentTimeMillis() + ".xls";

		//创建目录
		File dirFile = new File(downloadPath);
		if (dirFile.exists()) {
			if (!dirFile.isDirectory()) {
				dirFile.mkdir();
			}
		} else {
			dirFile.mkdir();
		}
		
		Map<String, String> columns = new LinkedHashMap<String, String>();
		columns.put("coupon_id", "优惠券批次");
		//columns.put("id", "优惠券ID");
		columns.put("coupon_name", "优惠券名称");
		columns.put("cash_money", "优惠券金额");
		columns.put("coupon_type_name", "优惠券类型");
		columns.put("coupon_code", "优惠券兑换码");
		columns.put("coupon_short_url", "兑换短链接");
		columns.put("coupon_code_url", "兑换地址");
//		columns.put("use_begin_date", "有效期开始");
//		columns.put("use_end_date", "有效期结束");
//		columns.put("get_time", "兑换时间");
//		columns.put("use_time", "使用时间");
		ExcelDocumentor documentor = new ExcelDocumentor();
		documentor.exportTable(list, columns, new File(downloadPath+File.separator+fileName));
		return fileName;
	}
	
	/**
	 * 添加优惠券明细 这里只是现金券 其余的券还没有添加如果有业务需求在添加
	 * 
	 */
	@Override
	public String insertOrUpdateCouponDetailBy(CouponInfo couponInfo, Integer userId, CouponDetail couponDetail,
			boolean bInsert, Map<String, Object> retMap) {
		if (CouponConstants.CouponStatus_Online == couponInfo.getCouponStatus()){  //2表示上架中
			if(couponInfo.getMaxCount() != 0 && couponInfo.getGetedCount() >= couponInfo.getMaxCount()){ //已领满
				return "已领满";
			}
			Date currDate= DateUtils.getDateShort(new Date());
			if(couponInfo.getChangeMode() == 2){//2表示限制兑换时间
				if(retMap != null){
					retMap.put("change_begin_date", DateUtils.toDateString(couponInfo.getChangeBeginDate()));
					retMap.put("change_end_date", DateUtils.toDateString(couponInfo.getChangeEndDate()));
				}

				if(currDate.before(couponInfo.getChangeBeginDate())){
					return "该券还未到兑换时间";  //该券还未到兑换时间
				}else if (currDate.after(couponInfo.getChangeEndDate())){
					return "该券的兑换时间已过";  //该券的兑换时间已过
				}
			}
			
			int isUsed = 0;			//默认未使用
			int isGeted = 1;		//插入一张固定口令券，1表示已领取
			Date useBeginDate=couponInfo.getUseBeginDate();  //默认：把生效时间从主表复制一份到detail表  
			Date useEndDate=couponInfo.getUseEndDate();
			Date now = DateUtils.getDateShort(new Date());  //只取年月日
            Map<String,Object> resultMap = null;
            Date vipStartDate = couponInfo.getUseBeginDate();
            Date vipEndDate = couponInfo.getUseEndDate();
			if (CouponConstants.UseMode_Now == couponInfo.getUseMode()) { //立即生效: 从领取之日开始计算
				if (couponInfo.getDayNum() > 0) {
					useBeginDate = now;  //立即生效，则开始时间从现在开始算
					Calendar ca = Calendar.getInstance();
					ca.add(Calendar.DATE, couponInfo.getDayNum() - 1);//增加的天数
					useEndDate = DateUtils.getDateShort(ca.getTime());
				}
			}	
			if(retMap != null){
				retMap.put("code_type", couponInfo.getCouponType());
			}
			//添加一条领取记录（固定口令：到这里必定是需要插入的，前面已经判断了是否领过）
			try{
				if (couponDetail==null){
					couponDetail = new CouponDetail();
				}
				couponDetail.setCouponId(couponInfo.getId());
				
				if(bInsert){  //插入时才用重新生成兑换券
					couponDetail.setCouponCode(generatorCouponCodeBy(couponInfo.getId()));
					couponDetail.setMakeTime(new Date());
				}

				couponDetail.setIsGeted(isGeted);  //设为已领取
				if(isGeted == 1){
					couponDetail.setGetTime(new Date());
				}
				couponDetail.setUserId(userId);
				couponDetail.setIsUsed(isUsed); //设为未使用
				couponDetail.setUseBeginDate(useBeginDate);
				couponDetail.setUseEndDate(useEndDate);
				if(isUsed ==1){
					couponDetail.setUseTime(new Date());
				}
				
				if(bInsert == true){
					couponDetailMapper.insertSelective(couponDetail);

				}else{
					couponDetailMapper.updateByPrimaryKeySelective(couponDetail);
				}
				//券的领取人数加1
				couponInfo.setGetedCount(couponInfo.getGetedCount() + 1);
				couponInfoMapper.updateSelectiveById(couponInfo);
				return "Ok";
				
			}catch(Exception e){
				e.printStackTrace();
				throw new RuntimeException();
			}
			
		}
		return "OK";
	}
}
